package com.ryzx.log.collector;


import com.ryzx.common.feign.IDGeneratorFeign;
import com.ryzx.common.util.JsonUtil;
import com.ryzx.common.util.StringUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;


/*
日志处理抽象类，用于封装日志处理公用方法
 */
public abstract class AbstractLogHandler {
    @Resource
    IDGeneratorFeign idGeneratorFeign;
    protected HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        return attributes.getRequest();
    }
    protected String processRequestTraceId() {
        HttpServletRequest request = this.getRequest();
        String traceId = request.getHeader(LogComponentConstant.TRACE_ID);
        if (StringUtil.isBlank(traceId)) {
            traceId = String.valueOf(idGeneratorFeign.nextId());
        }
        RequestLogContext.addTraceId(traceId);
        return traceId;
    }
    protected boolean isOutPutLog(Object[] params) {
        boolean outputMark = this.isMultilFileMark(params);
        return !outputMark;
    }
    protected boolean isMultilFileMark(Object[] params) {
        boolean multilFileMark = false;
        for (Object param : params) {
            if (param instanceof MultipartFile) {
                multilFileMark = true;
                break;
            }
        }
        return multilFileMark;
    }
    protected String getTimeCostFlag(long cost) {
        return TimeCostEnum.costMark(cost);
    }
    protected MethodLogInfo buildMethodInfo(JoinPoint point) {
        HttpServletRequest request = this.getRequest();
        String path = request.getRequestURL().toString();
        String className = point.getSignature().getDeclaringTypeName();
        String method = request.getMethod();
        String methodName = point.getSignature().getName();
        Object[] params = point.getArgs();
        boolean multilFileMark = this.isMultilFileMark(params);
        MethodLogInfo requestLogInfo = new MethodLogInfo();
        requestLogInfo.setPath(path);
        requestLogInfo.setClassName(className);
        requestLogInfo.setMethod(method);
        requestLogInfo.setMethodName(methodName);
        if (!multilFileMark) {
            String paramsStr = JsonUtil.obj2String(params);
            requestLogInfo.setParamsStr(paramsStr);
        } else {
            requestLogInfo.setMultiFileMark(true);
        }
        return requestLogInfo;
    }
}